<template>
  <div class="tag-manager">
    <div class="tag-manager-header">
      <h2>标签管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新建标签
      </el-button>
    </div>
    
    <div class="tag-manager-content">
      <!-- 搜索栏 -->
      <div class="tag-search">
        <el-input
          v-model="searchQuery"
          placeholder="搜索标签..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <!-- 标签列表 -->
      <div class="tag-list" v-loading="loading">
        <div
          v-for="tag in filteredTags"
          :key="tag.id"
          class="tag-item"
          :class="{ 'tag-selected': selectedTags.includes(tag.id) }"
          @click="toggleTagSelection(tag.id)"
        >
          <div class="tag-color" :style="{ backgroundColor: tag.color }"></div>
          <div class="tag-info">
            <div class="tag-name">{{ tag.name }}</div>
            <div class="tag-count">{{ tag.photoCount || 0 }} 张照片</div>
          </div>
          <div class="tag-actions">
            <el-button type="text" @click.stop="editTag(tag)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button type="text" @click.stop="deleteTag(tag)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        
        <!-- 空状态 -->
        <EmptyState
          v-if="!loading && filteredTags.length === 0"
          type="tag"
          description="没有找到标签"
        >
          <el-button type="primary" @click="showCreateDialog">
            创建第一个标签
          </el-button>
        </EmptyState>
      </div>
      
      <!-- 分页 -->
      <div class="tag-pagination" v-if="total > pageSize">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 批量操作 -->
    <div class="tag-batch-actions" v-if="selectedTags.length > 0">
      <div class="batch-info">
        已选择 {{ selectedTags.length }} 个标签
      </div>
      <div class="batch-actions">
        <el-button @click="clearSelection">取消选择</el-button>
        <el-button type="danger" @click="batchDeleteTags">删除所选</el-button>
      </div>
    </div>
    
    <!-- 创建/编辑标签对话框 -->
    <el-dialog
      v-model="tagDialogVisible"
      :title="isEditing ? '编辑标签' : '创建标签'"
      width="500px"
    >
      <el-form
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagFormRules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <div class="color-picker-container">
            <el-color-picker v-model="tagForm.color" />
            <div class="preset-colors">
              <div
                v-for="color in presetColors"
                :key="color"
                class="preset-color"
                :style="{ backgroundColor: color }"
                @click="tagForm.color = color"
              ></div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="标签描述">
          <el-input
            v-model="tagForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTag" :loading="saving">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { ElButton, ElIcon, ElInput, ElLoading, ElMessage, ElDialog, ElForm, ElFormItem, ElColorPicker, ElPagination } from 'element-plus';
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue';
import type { Tag } from '@/types';
import { tagService } from '@/services/tagService';
import EmptyState from '@/components/ui/EmptyState.vue';

// 组件状态
const loading = ref(false);
const saving = ref(false);
const tags = ref<Tag[]>([]);
const selectedTags = ref<string[]>([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 标签对话框
const tagDialogVisible = ref(false);
const isEditing = ref(false);
const tagFormRef = ref();

// 标签表单
const tagForm = reactive({
  id: '',
  name: '',
  color: '#409EFF',
  description: ''
});

// 表单验证规则
const tagFormRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
};

// 预设颜色
const presetColors = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
  '#722ED1', '#EB2F96', '#FA541C', '#13C2C2', '#52C41A',
  '#1890FF', '#2F54EB', '#722ED1', '#F5222D', '#FA8C16'
];

// 计算属性：过滤后的标签
const filteredTags = computed(() => {
  if (!searchQuery.value) {
    return tags.value;
  }
  
  const query = searchQuery.value.toLowerCase();
  return tags.value.filter(tag => 
    tag.name.toLowerCase().includes(query) || 
    (tag.description && tag.description.toLowerCase().includes(query))
  );
});

// 加载标签列表
const loadTags = async () => {
  try {
    loading.value = true;
    const response = await tagService.getTags({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value
    });
    
    tags.value = response.data;
    total.value = response.total;
  } catch (error) {
    ElMessage.error('加载标签失败');
    console.error('加载标签失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadTags();
};

// 页码变化处理
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadTags();
};

// 每页大小变化处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadTags();
};

// 切换标签选择状态
const toggleTagSelection = (tagId: string) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tagId);
  }
};

// 清除选择
const clearSelection = () => {
  selectedTags.value = [];
};

// 显示创建标签对话框
const showCreateDialog = () => {
  isEditing.value = false;
  resetTagForm();
  tagDialogVisible.value = true;
};

// 编辑标签
const editTag = (tag: Tag) => {
  isEditing.value = true;
  tagForm.id = tag.id;
  tagForm.name = tag.name;
  tagForm.color = tag.color;
  tagForm.description = tag.description || '';
  tagDialogVisible.value = true;
};

// 重置标签表单
const resetTagForm = () => {
  tagForm.id = '';
  tagForm.name = '';
  tagForm.color = '#409EFF';
  tagForm.description = '';
  
  // 重置表单验证
  if (tagFormRef.value) {
    tagFormRef.value.clearValidate();
  }
};

// 保存标签
const saveTag = async () => {
  try {
    // 表单验证
    const valid = await tagFormRef.value.validate();
    if (!valid) return;
    
    saving.value = true;
    
    if (isEditing.value) {
      // 更新标签
      await tagService.updateTag(tagForm.id, {
        name: tagForm.name,
        color: tagForm.color,
        description: tagForm.description
      });
      ElMessage.success('标签更新成功');
    } else {
      // 创建标签
      await tagService.createTag({
        name: tagForm.name,
        color: tagForm.color,
        description: tagForm.description
      });
      ElMessage.success('标签创建成功');
    }
    
    // 关闭对话框并重新加载标签
    tagDialogVisible.value = false;
    loadTags();
  } catch (error) {
    ElMessage.error(isEditing.value ? '标签更新失败' : '标签创建失败');
    console.error('保存标签失败:', error);
  } finally {
    saving.value = false;
  }
};

// 删除标签
const deleteTag = async (tag: Tag) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签 "${tag.name}" 吗？删除后不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await tagService.deleteTag(tag.id);
    ElMessage.success('标签删除成功');
    
    // 从选择列表中移除
    const index = selectedTags.value.indexOf(tag.id);
    if (index > -1) {
      selectedTags.value.splice(index, 1);
    }
    
    // 重新加载标签
    loadTags();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('标签删除失败');
      console.error('删除标签失败:', error);
    }
  }
};

// 批量删除标签
const batchDeleteTags = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTags.value.length} 个标签吗？删除后不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await tagService.batchDeleteTags(selectedTags.value);
    ElMessage.success('标签批量删除成功');
    
    // 清除选择
    selectedTags.value = [];
    
    // 重新加载标签
    loadTags();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('标签批量删除失败');
      console.error('批量删除标签失败:', error);
    }
  }
};

// 组件挂载后加载标签
onMounted(() => {
  loadTags();
});
</script>

<style scoped lang="scss">
.tag-manager {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .tag-manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }
  
  .tag-manager-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 16px 24px;
    overflow: hidden;
    
    .tag-search {
      margin-bottom: 16px;
    }
    
    .tag-list {
      flex: 1;
      overflow-y: auto;
      
      .tag-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        margin-bottom: 8px;
        border-radius: 8px;
        cursor: pointer;
        transition: background-color 0.2s;
        
        &:hover {
          background-color: var(--el-color-primary-light-9);
        }
        
        &.tag-selected {
          background-color: var(--el-color-primary-light-8);
        }
        
        .tag-color {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          margin-right: 12px;
          flex-shrink: 0;
        }
        
        .tag-info {
          flex: 1;
          
          .tag-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .tag-count {
            font-size: 12px;
            color: var(--el-text-color-secondary);
          }
        }
        
        .tag-actions {
          display: flex;
          gap: 4px;
          opacity: 0;
          transition: opacity 0.2s;
          
          .el-button {
            padding: 6px;
          }
        }
        
        &:hover .tag-actions {
          opacity: 1;
        }
      }
    }
    
    .tag-pagination {
      margin-top: 16px;
      display: flex;
      justify-content: center;
    }
  }
  
  .tag-batch-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 24px;
    background-color: var(--el-color-primary-light-9);
    border-top: 1px solid var(--el-border-color-light);
    
    .batch-info {
      font-size: 14px;
      color: var(--el-text-color-primary);
    }
    
    .batch-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .color-picker-container {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .preset-colors {
      display: flex;
      gap: 8px;
      
      .preset-color {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        cursor: pointer;
        transition: transform 0.2s;
        
        &:hover {
          transform: scale(1.2);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .tag-manager {
    .tag-manager-header {
      padding: 12px 16px;
      
      h2 {
        font-size: 18px;
      }
    }
    
    .tag-manager-content {
      padding: 12px 16px;
      
      .tag-list {
        .tag-item {
          padding: 10px 12px;
          
          .tag-color {
            width: 20px;
            height: 20px;
            margin-right: 10px;
          }
          
          .tag-info {
            .tag-name {
              font-size: 14px;
            }
            
            .tag-count {
              font-size: 11px;
            }
          }
          
          .tag-actions {
            opacity: 1;
          }
        }
      }
    }
    
    .tag-batch-actions {
      padding: 10px 16px;
      
      .batch-info {
        font-size: 12px;
      }
    }
  }
}
</style>